<?php

namespace Hdphim\Modules\Admin\Controllers;
use Hdphim\Modules\Api\Models\Users\UsersGroups;
use Hdphim\Modules\Admin\Models\Users\Permissions;

class PermissionsController extends \Hdphim\Library\Controllers\BackendController
{
    public function indexAction()
    {
        if($this->request->isPost())
        {
            $group = UsersGroups::findFirstById($this->request->getPost('groups_id'));
            
            if($group)
            {
                if($this->request->hasPost('permissions'))
                {
                    $group->getPermissions()->delete();
                    // Save the new permissions
                    foreach ($this->request->getPost('permissions') as $permission) 
                    {                        
                        $parts = explode('.', $permission);
                        $permission = new Permissions();
                        $permission->setGroupId($group->getId());
                        $permission->setResource($parts[0]);
                        $permission->setAction($parts[1]);
                        $permission->save();
                    }
                    $this->flash->success('Permissions were updated with success');
                }
                // Rebuild the ACL with
                $this->acl->rebuild();

                // Pass the current permissions to the view
                $this->view->permissions = $this->acl->getPermissions($group);
            }            	 
            $this->view->group = $group;
        }
        
        // Pass all the active profiles
        $this->view->groups = UsersGroups::find('active = "Y"');
    }
}